import { OriginRoute } from "@/router";
import { UserState } from "../types";
import { USER_INFO_KEY, USER_TOKEN_KEY, USER_REFRESH_TOKEN_KEY, MENU_ID} from "../localtions";
import { Canceler } from "axios";
import {toTreeData} from "@/utils"


// 默认用户信息
const userInfo: UserState = JSON.parse(
  sessionStorage.getItem(USER_INFO_KEY) || "{}"
);

// 用户状态管理
const useUserStore = defineStore("user", {
  state: () => {
    return {
      token: sessionStorage.getItem(USER_TOKEN_KEY) || "",
      refreshToken: sessionStorage.getItem(USER_REFRESH_TOKEN_KEY) || "",
      menus: [] as Array<OriginRoute>,
      isHasGetInfo: false,
      userInfo: userInfo,
      _axiosPromiseCancel: new Map, //取消所有的未完成请求
    };
  },
  getters: {},
  actions: {    
    // 存储用户信息
    saveUser(userInfo: UserState) {
      this.userInfo = {
        ...userInfo
      };
      
      this.isHasGetInfo = true;
      // 缓存用户信息
      sessionStorage.setItem(USER_INFO_KEY, JSON.stringify(this.userInfo));
    },

    // 保存菜单
    saveMenus(data: OriginRoute[], pid: string, id: string) {
      // 将用户菜单根据子父关系组合
      const d: Array<OriginRoute> = toTreeData(data, pid, id);
      this.menus = d;
    },

    // 清空用户信息
    removeUserInfo() {
      this.token = "";
      this.refreshToken = "";
      sessionStorage.removeItem(USER_TOKEN_KEY);
      sessionStorage.removeItem(USER_REFRESH_TOKEN_KEY);
      this.menus = [] as Array<OriginRoute>;
      this.isHasGetInfo = false;
      this.userInfo = userInfo;
      sessionStorage.removeItem(USER_INFO_KEY);
      sessionStorage.removeItem(MENU_ID);
    },
    // 收集页面请求
    pushCancel(questKey:string,payload: Canceler) {
      this._axiosPromiseCancel.set(questKey,payload)
    },
    removeCancel(questKey:string){
      this._axiosPromiseCancel.delete(questKey)
    },
    // 清除上个页面的所有请求
    clearAllRequest() {
      this._axiosPromiseCancel.forEach((value, key) => {
        value()
      });
      this._axiosPromiseCancel.clear();
    },

    // 更新用户状态
    updateHasGetInfo() {
      this.isHasGetInfo = true;
    },

    //保存token
    saveToken(token :string, refreshToken: string){      
      // 缓存token
      this.token = token;
      this.refreshToken = refreshToken;
      sessionStorage.setItem(USER_TOKEN_KEY, token);
      sessionStorage.setItem(USER_REFRESH_TOKEN_KEY, refreshToken);
    }
  },
});


export default useUserStore;